package core;

import gitobject.Commit;
import gitobject.Tree;
import repository.Repository;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.*;

public class JitCommit {
	/**
	 * Add files into your index.
	 * @param message
	 * @throws IOException
	 */
	@SuppressWarnings("unused")
	public static void commit(String message) throws IOException {
		/* Todo: You should pass the filename in this function, and generate a hash file in your repository.
		 *   Add your code here.*/
		/*获取当前时间并按特定格式保存*/
		String timestamp = Long.toString(System.currentTimeMillis() / 1000);
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("Z");
		Date date = new Date(System.currentTimeMillis());
		String time = simpleDateFormat.format(date);
		/* End */
		String[] userinfo = new String[2];
		readUserInfo(userinfo);
		try {
			Tree commitTree = new Tree(".");
			Set<Map.Entry<String, String>> addedItemsSet = JitMap.index.getMapValues();
			for (Map.Entry<String, String> item : addedItemsSet) {
				String keyPath = item.getKey();
				String path = keyPath.replace(Tree.treeSeparator, File.separator);
				String content = item.getValue();
				Tree finalTree = commitTree.makeTree(path);
				finalTree.addBlobFromIndex(content);
			}
			JitMap.setIndexMap();
			String commitTreeKey = commitTree.buildTree();
			if(Objects.equals(commitTree.getValue(), "")){
				System.out.println("nothing to commit, working tree clean\n");
			}
			else {
				Commit commit = new Commit(commitTreeKey, userinfo[0] + userinfo[1] + timestamp + " " + time, userinfo[0] + userinfo[1] + timestamp + " " + time, message);
				if(commit.writeToHead() == null){
					System.out.println("Head is not exist");
				}
				else{
					JitMap.safeCommitIndex();
					JitMap.index.compressWrite();
				}
			}
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	}

	public static void readUserInfo(String[] userinfo) throws IOException{
		File user = new File(Repository.getGitDir() + File.separator + ".jitConfig");
		if(user.exists()){
			try {
				FileInputStream is = new FileInputStream(user);
				BufferedReader br = new BufferedReader(new InputStreamReader(is));
				String line = br.readLine();
				while (line != null){
					if(line.contains("name")){
						userinfo[0] = line.split(" ")[2];
					}
					else if(line.contains("email")){
						userinfo[1] = " <" + line.split(" ")[2] + "> ";
					}
					line=br.readLine();
				}
				br.close();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		else {
			System.out.println("Username is not be set, please check");
			throw new IOException("Username is not be set, please check");
		}
	}
}